#!/bin/bash

# MySQL安装包所在路径，需要带上包名。示例：PACKAGE_FULL_PATH=/root/mysql-5.7.33-linux-glibc2.12-x86_64.tar.gz
readonly PACKAGE_FULL_PATH=/root/mysql-5.7.33-linux-glibc2.12-x86_64.tar.gz
# MySQL安装主目录。示例：INSTALL_HOME=/usr/local/mysql
readonly INSTALL_HOME=/usr/local/mysql
# MySQL数据库root用户密码。示例：123456
readonly USER_PASSWD=123456

# 检查是否为root用户
if [[ "$UID" -ne 0 ]]; then
    echo "ERROR: the script must run as root"
    exit 3
fi

# 记录常规日志
function log_info(){
    echo "[$(date -d today +"%Y-%m-%d %H%M%S %:::z")] $1"
}

# 记录异常日志
function log_error(){
    echo -e "[$(date +"%Y-%m-%d %H%M%S %Z%:z")] [ERROR] $* \n"
    exit 1
}

# 检查结果
function check_result(){
    local ret_code=$1
    shift
    local error_msg=$*
    if [[ ${ret_code} -ne 0 ]]; then
        log_error ${error_msg}
    fi
}

# 校验参数
function check_param(){
    if [[ ! -n ${PACKAGE_FULL_PATH} ]] || [[ ! -n ${INSTALL_HOME} ]] || [[ ! -n ${USER_PASSWD} ]]; then
        log_error "Param: PACKAGE_FULL_PATH INSTALL_HOME USER_PASSWD can not be null"
    fi
    if [[ ! -f ${PACKAGE_FULL_PATH} ]]; then
        log_error "Param: PACKAGE_FULL_PATH is not a directory"
    fi
}

# 检查mysql进程是否存在
function check_mysql_process(){
    local mysql_process_count=`ps -ef | grep ${INSTALL_HOME} | grep -vwE "grep|vi|vim|tail|cat" | wc -l`
    if [[ ${mysql_process_count} -gt 0 ]]; then
        log_error "Please stop and uninstall the mysql first"
    fi
}

# 新建mysql用户组，mysql用户
function add_user(){
    # create group mysql
    grep "^mysql" /etc/group &> /dev/null
    if [[ $? -ne 0 ]]; then
        groupadd mysql
    fi
    # create user mysql
    id mysql &> /dev/null
    if [[ $? -ne 0 ]]; then
        useradd -r -g mysql -s /bin/false mysql
    fi
}

# 初始化my.cnf
function init_my_cnf(){
echo "
[mysql]
default-character-set=utf8mb4

[mysqld]
character_set_server=utf8mb4

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
" > /etc/my.cnf
}


# 安装MySQL
function install_mysql(){

    rpm -e --nodeps $(rpm -qa | grep mariadb)

    # 创建安装主目录
    mkdir -p ${INSTALL_HOME}
    # 解压mysql安装包到安装主目录
    tar -zxvf ${PACKAGE_FULL_PATH} -C ${INSTALL_HOME} > /dev/null 2>&1
    echo ">>> tar finish"
    check_result $? "unzip MySQL package error"
    local package_name=`ls ${INSTALL_HOME} | grep mysql`
    mv ${INSTALL_HOME}/${package_name}/* ${INSTALL_HOME}
    rm -rf ${INSTALL_HOME}/${package_name}
    cd ${INSTALL_HOME}

    # 创建一个自由目录，可用于dump等操作
    mkdir mysql-files
    chown mysql:mysql mysql-files
    chmod 750 mysql-files

    # 安装并指定用户
    ./bin/mysqld --initialize-insecure --user=mysql
    echo ">>> mysqld finish"
    ./bin/mysql_ssl_rsa_setup
    ./bin/mysqld_safe --user=mysql &
    echo ">>> mysqld_safe finish"

    # 初始化my.cnf
    init_my_cnf

    #配置自启动
    cp -pf ${INSTALL_HOME}/support-files/mysql.server /etc/init.d/mysql.server
    chmod 755 /etc/init.d/mysql.server
    systemctl daemon-reload
    chkconfig --add mysql.server

    # 添加环境变量
    echo "### MySQL_PATH_ENV_S" >> /etc/profile
    echo "export PATH=${INSTALL_HOME}/bin:\$PATH" >> /etc/profile
    echo "### MySQL_PATH_ENV_E" >> /etc/profile

    # 启动MySQL
    echo ">>> Start MySQL"
    start

    sleep 3

    cd ${INSTALL_HOME}
# 修改MySQL用户的root密码
./bin/mysql -uroot << EOF
ALTER USER 'root'@'localhost' IDENTIFIED BY '${USER_PASSWD}';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '${USER_PASSWD}' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EOF
}

# 启动MySQL
function start() {
    systemctl start mysql
}

# 停止MySQL
function stop() {
    systemctl stop mysql
}

# 检查MySQL状态
function status() {
    systemctl status mysql
}

# 安装MySQL
function install() {
    log_info "++++++++++ step 1 ++++++++++"
    check_param
    log_info "check_param finish"

    log_info "++++++++++ step 2 ++++++++++"
    check_mysql_process
    log_info "check_mysql_process finish"

    log_info "++++++++++ step 3 ++++++++++"
    add_user
    log_info "add_user finish"

    log_info "++++++++++ step 4 ++++++++++"
    install_mysql
    log_info "install_mysql finish"
}

# 卸载MySQL
function uninstall() {
    # 如果MySQL仍启动则停止
    local mysql_process_count=`ps -ef | grep ${INSTALL_HOME} | grep -vwE "grep|vi|vim|tail|cat" | wc -l`
    if [[ ${mysql_process_count} -gt 0 ]]; then
        stop
    fi

    # 删除创建的文件
    rm -rf ${INSTALL_HOME}
    rm -rf /etc/init.d/mysql.server
    rm -rf /etc/my.cnf
    rm -rf /tmp/mysql.sock*

    # 删除配置的环境变量
    sed -i '/### MySQL_PATH_ENV_S/,/### MySQL_PATH_ENV_E/d' /etc/profile

    # 删除用户和用户组
    id mysql &> /dev/null
    if [[ $? -eq 0 ]]; then
        userdel  mysql
    fi
    log_info "uninstall MySQL success"
}

# 命令帮助
function usage() {
    echo "Usage: $PROG_NAME {start|stop|restart|status|install|uninstall}"
    exit 2
}

# 主流程

PROG_NAME=$0
ACTION=$1

case "$ACTION" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    status)
        status
    ;;
    install)
        install
    ;;
    uninstall)
        uninstall
    ;;
    *)
        usage
    ;;
esac
